<template>
  <div class="amap-components">
    <div id="containers"></div>
    <el-autocomplete
      popper-class="my-autocomplete"
      class="autocomplete"
      v-model.trim="keyword"
      :fetch-suggestions="querySearch"
      :trigger-on-focus="false"
      highlight-first-item
      placeholder="请输入关键词获取地址"
      @select="handleSelect"
    >
      <template #default="{ item }">
        <div class="name">{{ item.value }}</div>
        <span class="addr">{{ item.district }}</span>
      </template>
    </el-autocomplete>
  </div>
</template>
<script setup name="AmapComponents">
import AMapLoader from '@amap/amap-jsapi-loader';
import { shallowRef } from 'vue';
import { reactive, nextTick, onMounted, ref, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import emitter from '@/utils/mitt';

const props = defineProps({
  longitude: {
    type: Number,
    default: null,
  },
  latitude: {
    type: Number,
    default: null,
  },
  address: {
    type: String,
    default: '',
  },
});
const { longitude, latitude, address } = toRefs(props);

// let geocoder, circleEditor;
// let AMap
const map = shallowRef(null);
const geocoder = shallowRef(null);
const circleEditor = shallowRef(null);
const marker = ref([]);
const center = ref([120.058645, 30.281449]);
const radius = ref(300);
const restaurants = ref([]);
const keyword = ref('');
const data = reactive({
  contextMenuPositon: {},
});
const { contextMenuPositon } = toRefs(data);

const initAmap = () => {
  AMapLoader.load({
    key: 'ec94e8ef1788100c417991ad05789c00', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.HawkEye',
      'AMap.ToolBar',
      'AMap.Geolocation',
      'AMap.Geocoder',
      'AMap.ContextMenu',
      'AMap.CircleEditor',
    ],
  })
    .then((amap) => {
      // AMap = amap;
      //地图加载
      map.value = new AMap.Map('containers', {
        zoom: 12, //设置地图显示的缩放级别
        center: center.value, //设置地图中心点坐标
        viewMode: '2D',
        mapStyle: 'amap://styles/9598c64f4ce3ffb9a69c7a0c59a5bffa',
        resizeEnable: true,
      });

      console.log(map.value, 'map.value');
      // map.value.on("click", (ev) => {
      //   // 触发事件的对象
      //   center.value = [ev.lnglat.lng, ev.lnglat.lat];
      //   getMap();
      // });
      setContextMenu();
      if (longitude.value && latitude.value) {
        getMap();
      } else {
        if (address.value) {
          geoAmapCoder();
        } else {
          geolocation(); //获取当前位置
        }
      }
      // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
      map.value.addControl(new AMap.ToolBar());

      // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
      map.value.addControl(new AMap.HawkEye({ isOpen: true }));

      // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
      map.value.addControl(new AMap.Geolocation({ position: 'LB' }));

      emitter.emit('initScroll');
    })
    .catch((e) => {
      console.log(e);
    });
};
const handleSelect = (item) => {
  center.value = item.center;
  map.value.setZoomAndCenter(15, center.value);
};
const querySearch = (queryString, cb) => {
  console.log('querySearch');
  // 输入提示与POI搜索
  AMap.plugin('AMap.AutoComplete', () => {
    var autoOptions = {
      //city 限定城市，默认全国
      city: '全国',
    };
    // 实例化AutoComplete
    var autoComplete = new AMap.AutoComplete(autoOptions);
    console.log(autoComplete, 'POI搜索');
    // 根据关键字进行搜索 _that.keyword
    autoComplete.search(queryString, function (status, result) {
      console.log(status, result);
      // 搜索成功时，result即是对应的匹配数据
      let arr = [];
      if (status == 'complete') {
        result.tips.forEach((element) => {
          if (element.location) {
            arr.push({
              value: element.name,
              district: element.district,
              center: [element.location.lng, element.location.lat],
            });
          }
        });
        restaurants.value = arr;
        cb(arr);
      }
    });
  });
};
// 标记当前位置
const getMap = () => {
  marker.value = [...center.value];
  let marker1 = new AMap.Marker({
    position: new AMap.LngLat(center.value[0], center.value[1]),
  });
  map.value.clearMap(); //清除所有覆盖物
  map.value.add(marker1);
  map.value.setZoomAndCenter(15, center.value);
};
// 获取当前位置
const geolocation = () => {
  AMap.plugin('AMap.Geolocation', () => {
    var geolocation = new AMap.Geolocation({
      // 是否使用高精度定位，默认：true
      enableHighAccuracy: true,
      // 设置定位超时时间，默认：无穷大
      timeout: 10000,
      // 定位按钮的停靠位置的偏移量
      offset: [10, 20],
      //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      zoomToAccuracy: false,
      //  定位按钮的排放位置,  RB表示右下
      position: 'LB',
      showButton: true,
    });
    geolocation.getCurrentPosition((status, result) => {
      console.log(result);
      if (status == 'complete') {
        onComplete(result);
      } else {
        onError(result);
      }
    });

    // _that.map.value.addControl(geolocation);

    function onComplete(data) {
      // console.log(data);
      // data是具体的定位信息
      let { lng, lat } = { ...data.position };
      center.value = [lng, lat];
      getMap();
    }

    function onError(data) {
      // 定位出错
      ElMessage({
        type: 'info',
        message: '无法获取当前位置',
      });
    }
  });
};
// 地理编码
const geoAmapCoder = () => {
  geocoder.value = new AMap.Geocoder();
  geocoder.value.getLocation(address.value, (status, result) => {
    if (status === 'complete' && result.geocodes.length) {
      console.log(
        '%c [ result ]-190',
        'font-size:13px; background:pink; color:#bf2c9f;',
        result,
      );
      let { lat, lng } = { ...result.geocodes[0].location };
      center.value = [lng, lat];
      getMap();
    } else {
      ElMessage({
        type: 'info',
        message: '根据地址查询位置失败',
      });
    }
  });
};
// 绘制电子围栏
const setScope = () => {
  var circle = new AMap.Circle({
    center: new AMap.LngLat(center.value[0], center.value[1]), // 圆心位置
    radius: radius.value, // 圆半径
    fillColor: '#1791fc', // 圆形填充颜色
    strokeOpacity: 0.3, //边框线透明度
    strokeColor: '#3366FF', // 描边颜色
    strokeWeight: 2, // 描边宽度
    fillOpacity: 0.35, //填充透明度
  });
  map.value.setZoomAndCenter(16, center.value);
  map.value.add(circle);

  circleEditor.value = new AMap.CircleEditor(map.value, circle);
  circleEditor.value.open();
  circleEditor.value.on('adjust', (event) => {
    radius.value = event.radius;
  });
  circleEditor.value.on('move', (event) => {
    center.value = [event.lnglat.lng, event.lnglat.lat];
  });
};

// 自定义右键菜单
const setContextMenu = () => {
  var contextMenu = new AMap.ContextMenu();
  contextMenu.addItem(
    '设置电子为栏',
    () => {
      map.value.clearMap();
      if (circleEditor.value) {
        circleEditor.value.close();
      }
      center.value = [
        contextMenuPositon.value.lng,
        contextMenuPositon.value.lat,
      ];
      setScope();
      contextMenu.close();
    },
    1,
  );
  contextMenu.addItem(
    '设置点位',
    () => {
      map.value.clearMap();
      if (circleEditor.value) {
        circleEditor.value.close();
      }
      center.value = [
        contextMenuPositon.value.lng,
        contextMenuPositon.value.lat,
      ];
      getMap();
      contextMenu.close();
    },
    2,
  );
  map.value.on('rightclick', (e) => {
    contextMenu.open(map.value, e.lnglat);
    contextMenuPositon.value = e.lnglat;
  });
};

onMounted(() => {
  if (longitude.value && latitude.value) {
    center.value = [longitude.value, latitude.value];
  }
  window._AMapSecurityConfig = {
    // 设置安全密钥
    securityJsCode: 'ea8e03ab0b74682da814c6556a811426',
  };
  nextTick(() => {
    initAmap();
  });
});
</script>

<style lang="scss" scoped>
#containers {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}
.amap-components {
  width: 100%;
  height: 500px;
  position: relative;
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
::v-deep {
  .el-autocomplete {
    display: inline-block;
    position: absolute;
    top: 20px;
    left: 20px;
  }
  .amap-copyright {
    display: none !important;
  }
  .amap-menu-outer {
    color: #000;
  }
  .amap-marker-label {
    color: #000;
  }
}
</style>
